/*  File Name	: SocketPair.cpp
 *  Author		: Pang Jiacai
 *	 E-mail		: 823960168@qq.com
 *  Created on	: 2012-6-27
 *  Description:
 */

#include "SocketPair.h"
#include "EventHandler.h"
#include <string>

SocketPair::SocketPair()
{

}

SocketPair::~SocketPair()
{

}

int SocketPair::socketpair(int fd[2],int family,int type,int protocol)
{
	return ::socketpair(family,type,protocol,fd);
}

int SocketPair::socketpair_set_reuse(int fd)
{
	int flag = 1;
	return ::setsockopt(fd,SOL_SOCKET,SO_REUSEADDR, (void*)&flag,(int)sizeof(flag));
}

int SocketPair::socketpair_set_nonblock(int fd)
{
	int val = ::fcntl(fd, F_GETFL, 0);
	if (val == -1)
	{
		return -1;
	}
	SET_BITS(val, O_NONBLOCK);
	return ::fcntl(fd, F_SETFL, val);
}

int SocketPair::socketpair_set_block(int fd)
{
	int val = ::fcntl(fd, F_GETFL, 0);
	if (val == -1)
	{
		return -1;
	}
	CLR_BITS(val, O_NONBLOCK);
	return ::fcntl(fd, F_SETFL, val);
}

int SocketPair::socketpair_close(int fd)
{
	if (fd < 0)
	{
		return -1;
	}
	return ::close(fd);
}

int SocketPair::socketpair_notify(int fd,char *buf,int len)
{
	if(NULL==buf)
	{
		return -1;
	}
	int result = ::write(fd, buf,len);
	return (result < 0 && errno != EAGAIN) ? -1 : 0;
}

void SocketPair::socketpair_fd_reset(int fd[2])
{
    fd[0]=-1;
    fd[1]=-1;
}
